package afcp.alumni.csv;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import afcp.alumni.model.ExcelFileProperties;

public class ExcelReader implements FileReader {
	
	private InputStream inputStream;
	private HSSFSheet sheet;
	private Iterator<Row> rowIterator;
	
	public ExcelReader(InputStream inputStream, ExcelFileProperties properties) throws IOException {
		this.inputStream = inputStream;
		
		//Get the workbook instance for XLS file 
		HSSFWorkbook workbook = new HSSFWorkbook(inputStream, false);
		 
		//Get first sheet from the workbook
		sheet = workbook.getSheetAt(properties.getSheetNumber());
		 
		rowIterator = sheet.iterator();
		 
	}

	@Override
	public String[] readNext() throws IOException {

		//Get iterator to all the rows in current sheet
		if (!rowIterator.hasNext()) {
			return null;
		}
		List<String> cells = new LinkedList<>();

		//Get iterator to all cells of current row
//		Iterator<Cell> cellIterator = row.cellIterator();
		for (Cell cell : rowIterator.next()) {

			cells.add(cell.getStringCellValue());
			// TODO
//			switch (cell.getCellType()) {
//			case Cell.CELL_TYPE_BOOLEAN:
//				System.out.print(cell.getBooleanCellValue() + "\t\t");
//				break;
//			case Cell.CELL_TYPE_NUMERIC:
//				System.out.print(cell.getNumericCellValue() + "\t\t");
//				break;
//			case Cell.CELL_TYPE_STRING:
//				System.out.print(cell.getStringCellValue() + "\t\t");
//				break;
//			}
		}
		// TODO voir s'il est possible de stocker les formats numériques sans les convertir en String (puis plus tard en int)
		String[] result = cells.toArray(new String[cells.size()]);
		return result;
	}

	@Override
	public void close() throws IOException {
		inputStream.close();
	}

}
